package org.scratchcrew.web.upload;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.scratchcrew.domain.ScratchFile;
import org.scratchcrew.services.ScratchFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;

@Component(value = "file")
public class FileHandler implements HttpRequestHandler {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ScratchFileService scratchFileService;

	@Override
	public void handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String idParamter = request.getParameter("id");
		if (idParamter != null) {
			try {
				Long id = Long.valueOf(idParamter);
				logger.debug(String.format(
						"searching for file with " + "id %s", id));
				ScratchFile file = scratchFileService.find(id);
				if (file != null) {
					if (logger.isTraceEnabled()) {
						logger.trace(String.format("Checking modification"
								+ " dates for file with id %s", file.getId()));
					}
					long modifiedSince = request
							.getDateHeader("If-Modified-Since");
					if (logger.isDebugEnabled()) {
						logger.debug(String.format("borser modified since: %d,"
								+ " file last modified: %d", modifiedSince,
								file.getLastModifiedDate()));
					}
					if (-1 == modifiedSince
							|| modifiedSince < file.getLastModifiedDate()) {
						response.setContentType(file.getMimeType());
						response.setContentLength(file.getScratchFile().length);
						response.getOutputStream().write(file.getScratchFile());
						return;
					} else {
						logger.trace(String
								.format("Sending status code not"
										+ " modified for file with id %s", file
										.getId()));
						response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
						return;
					}
				} else {
					response.sendError(HttpServletResponse.SC_NOT_FOUND);
					return;
				}
			} catch (NumberFormatException e) {
				logger.error("cannot parse id request parameter", e);
			}
		}
		response.sendError(HttpServletResponse.SC_BAD_REQUEST);
	}

}
